import { director, sys } from "cc";
import Http from "./HTTP";
import { AudioMgr } from "./AudioMgr";
import { gameMgr } from "./gameMgr";

// const { ccclass, property } = cc._decorator;
const wx = window["wx"] || window["tt"]
export class Adsdk {
    bannerAd = null;
    bannerId: string = "";
  
    customLeftOneAd = null
    GridLeftId_1: string = ''

    customRightOneAd = null
    GridRightId_1: string = ''

    interstitialAd = null;
    interstitialId: string = '25d08o7aa25a2q0qpm'

    customTopId: string = ''
    customTopAd = null

    GridAdJz = null
    GridJzId: string = ''


    private GridLeftId_5
    private GridLeftId_4
    private GridLeftId_3

    private GridRightId_5
    private GridRightId_4
    private GridRightId_3

    private _gridAdLeft
    private _gridAdRight

    private _gridLfetId
    private _gridRightId

    private _windowWidth: number
    private _windowHeight: number
    private showGridJzTime: number
    private _adtop: number

    videoAdId: string = '1a273ac8ucl8ldd30j'

    ads

    constructor() {
       
    }
    private static _instance: Adsdk;

    static get instance(): Adsdk {
        if (this._instance == null) {
            this._instance = new Adsdk();
        }
        return this._instance;
    }


    public getWxIdFromServer(success,fail) {
        if (sys.platform != sys.Platform.WECHAT_GAME){
            fail && fail()
            return
        };
       
        try{
            console.log('getWxIdFromServer3')
            // @ts-ignore
            let appid = wx.getAccountInfoSync().miniProgram.appId
            Http.sendRequest('', {appid:appid,version:'1.1'}, (result) => {
                result.data = result.data.ads
                this.ads = result.data
                sys.localStorage.setItem('sdkads',this.ads);
                this.videoAdId = result.data.videoAdId
                this.interstitialId = result.data.interstitialId
                this.bannerId = result.data.bannerId
                this.GridLeftId_1 = result.data.gameCustomLeftId
                this.GridRightId_1 = result.data.gameCustomRightId
                success && success()
                console.log('广告请求成功')
            }, 'https://box.jiezhui.top/wxapp/xcxgame/getGameConfig.html', () => {
                console.log('请求错误')
                fail && fail()
            })
            
        }catch{
            fail && fail()
        }
    }
  

    init(){
        let sysInfo = wx.getSystemInfoSync()
        this._windowWidth = sysInfo.windowWidth
        this._windowHeight = sysInfo.windowHeight
        this._adtop = 150

        this.initInterstitialAd()
    }


    public showBanner(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        if(this._windowHeight<350)return
        if (!this.bannerAd) {
            this.createBanner(this.bannerId);
        }
        this.bannerAd.show();
    }

    public createBanner(bannerId: string) {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this.bannerAd = wx.createBannerAd({
            adUnitId: bannerId,
            adIntervals: 60,
            style: {
                width: this._windowWidth>250?250:this._windowWidth,
                left: this._windowWidth>250?(this._windowWidth-250)/2:0,
                top: 0
            }
        });


        if (!this.bannerAd) {
            return
        }

        this.bannerAd.onLoad(() => {
            this.showBanner()
        })

        //如果不需要让banner在底部，则注释掉onResize回调即可
        this.bannerAd.onResize(res => {
            this.bannerAd.style.top = this._windowHeight - this.bannerAd.style.realHeight;
        })

        this.bannerAd.onError((e) => {
            console.log('banner广告出错：'+e)
        })
    }

    
    public hideBanner(): void {
        if (!this.bannerAd) return;
        this.bannerAd.hide();
    }


    private createGridAdLeft(){
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this._gridAdLeft = wx.createCustomAd({
            adUnitId: this._gridLfetId,
            style: {
                left: 10,
                top: this._adtop,
                width: 100,
                fixed: true
            }
        })
        this._gridAdLeft.onError(err => {
            console.log('显示左边格子广告失败', err);
            console.error(err.errMsg)
            return
        });
        this._gridAdLeft.onLoad(() => {
            this.showGridAdLeft()
        })
    }


    //格子广告左边
    public showGridAdLeft(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        console.log("显示格子广告左边")

        if (!this._gridAdLeft) {
            this.createGridAdLeft()
            return
        }
        this._gridAdLeft.show().catch((err)=>{
            this.createGridAdLeft()
        })
       
    }

    public hideGridAdLeft() {
        if (this._gridAdLeft) {
            this._gridAdLeft.hide().catch((err) => {
                console.log('隐藏左边格子广告失败', err);
            })
        }
    }



    private createGridRight(){
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this._gridAdRight = wx.createCustomAd({
            adUnitId: this._gridRightId,
            style: {
                left: this._windowWidth-70,
                top: this._adtop,
                width: 100,
                fixed: true
            }
        })
        this._gridAdRight.onError(err => {
            console.log('显示右边格子广告失败', err);
            console.error(err.errMsg)
            return
        });
        this._gridAdRight.onLoad(() => {
            this.showGridAdRight()
        })
    }

    //格子广告右边
    public showGridAdRight(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        console.log("显示格子广告右边")
        if (!this._gridAdRight) {
            this.createGridRight()
            return
        }
        this._gridAdRight.show().catch((err)=>{
            this.createGridRight()
        })
    }

    public hideGridAdRight() {
        if (this._gridAdRight) {
            this._gridAdRight.hide().catch((err) => {
                console.log('隐藏右边格子广告失败', err);
            })
        }
    }


    getAds(){
        return this.ads
    }

    showVideo(success: any, fail: any) {
        if (sys.platform == sys.Platform.MOBILE_BROWSER
            || sys.platform == sys.Platform.DESKTOP_BROWSER) {
            success && success();
            if (gameMgr.ins.isHasAudio) {
                AudioMgr.ins.play("audio/bgm");
            }
            return
        }

        console.log('触发视频广告')
        let videoad = wx.createRewardedVideoAd({ adUnitId: this.videoAdId });
        videoad.onClose((res) => {
            console.log('video on close', res);
            if (res.isEnded) {
                success && success();
                if (gameMgr.ins.isHasAudio) {
                    AudioMgr.ins.play("audio/bgm");
                }
            } else {
                this.showToast('需要完整观看视频');
                fail && fail()
                if (gameMgr.ins.isHasAudio) {
                    AudioMgr.ins.play("audio/bgm");
                }
            }
            console.log('onClose销毁视频广告')
            // videoad.destroy();


        });
        videoad.onError((err) => {
            console.log('onError销毁视频广告')
            // videoad.destroy()
            fail && fail();
            if (gameMgr.ins.isHasAudio) {
                AudioMgr.ins.play("audio/bgm");
            }
            this.showToast('暂无广告');
        });
        videoad.onLoad(() => {
            console.log('视频广告加载成功')
        });

        videoad.show().catch(() => {
            videoad.load().then(() => videoad.show()).catch(err => {
                console.log('load')
                console.log(err)
            });

        });
    }

    initInterstitialAd() {
        if (wx) {
            console.log('createInterstitialAd1')
            if (wx.createInterstitialAd) {

                this.interstitialAd = wx.createInterstitialAd({ adUnitId: this.interstitialId })
                if (!this.interstitialAd) return;
                this.interstitialAd.onLoad(() => {
                    console.log('插屏初始化成功')
                    this.showInterstitialAd()
                })
                this.interstitialAd.onError((err) => {
                    console.log('interstitialAd onError event emit', err)
                })
                this.interstitialAd.onClose((res) => {
                    console.log('interstitialAd onClose event emit', res)
                })
            }
        }
    }


    showInterstitialAd() {
        if (this.interstitialAd) {
            this.interstitialAd.show().catch((err) => {
                // this.showGridAdJz()
                console.error(err)
            })
            
        }else{
            this.initInterstitialAd()
        }
    }

    private createGridJz(){
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this.GridAdJz = wx.createCustomAd({
            adUnitId: this.GridJzId,
            style: {
                top: 150,
                width: this._windowWidth,
                left: 0,
                fixed: true
            }
        })
        this.GridAdJz.onError(err => {
            console.log('显示矩阵格子广告失败', err);
            console.error(err.errMsg)
            return
        });
        this.GridAdJz.onLoad(() => {
            this.showGridAdJz()
        })
    }

     //格子广告矩阵
     public showGridAdJz(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        console.log("显示格子广告矩阵")

        if((Math.floor(new Date().getTime() / 1000))-this.showGridJzTime<15){
            console.log("显示格子广告矩阵时间太短")
            return
        }

        if (!this.GridAdJz) {
            this.createGridJz()
            return
        }
        this.GridAdJz.show().catch((err)=>{
            this.createGridJz()
        })

        this.showGridJzTime =  Math.floor(new Date().getTime() / 1000);

    }

    public hideGridAdJz() {
        if (this.GridAdJz) {
            this.GridAdJz.hide().catch((err) => {
                console.log('隐藏满屏格子广告失败', err);
            })
        }
    }


    private createGridLeftOne(){
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this.customLeftOneAd = wx.createCustomAd({
            adUnitId: this.GridLeftId_1,
            style: {
                left: 10,
                top: 80,
                width: 100,
                fixed: true
            }
        })
        this.customLeftOneAd.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.customLeftOneAd.onLoad(() => {
            this.showGridAdLeftOne()
        })
    }

    public showGridAdLeftOne(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        console.log('showGridAdLeftOne')
        if (!this.customLeftOneAd) {
            this.createGridLeftOne()
            return
        }
        this.customLeftOneAd.show().catch((err)=>{
            this.createGridLeftOne()
        })
    }

    public hideGridAdLeftOne() {
        if (this.customLeftOneAd) {
            this.customLeftOneAd.hide().catch((err) => {
            })
        }
    }


    private createGridRightOne(){
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        this.customRightOneAd = wx.createCustomAd({
            adUnitId: this.GridRightId_1,
            style: {
                left: this._windowWidth-70,
                top: this._windowHeight-150,
                width: 100,
                fixed: true
            }
        })
        this.customRightOneAd.onError(err => {
            console.error(err.errMsg)
            return
        });
        this.customRightOneAd.onLoad(() => {
            this.showGridAdRightOne()
        })
    }

    public showGridAdRightOne(): void {
        if (sys.platform != sys.Platform.WECHAT_GAME)return
        console.log('showGridAdRightOne ')
        if (!this.customRightOneAd) {
            console.log('showGridAdRightOne2')
            this.createGridRightOne()
            return
        }
        this.customRightOneAd.show().catch((err)=>{
            this.createGridRightOne()
        })
    }

    public hideGridAdRightOne() {
        if (this.customRightOneAd) {
            this.customRightOneAd.hide().catch((err) => {
            })
        }
    }



    showToast(str) {
        // if (!tt) {
        //     console.log(' show toast ', str)
        //     return
        // }
        wx.showToast({
            title: str,
            duration: 2000,
            icon: 'none',
            success(res) {
                console.log(`${res}`);
            },
            fail(res) {
                console.error(`showToast调用失败`);
            },
        });
    }


}



